﻿using System.Diagnostics;
using System.Windows;
using System.Windows.Controls.Primitives;

namespace AppToolkit.WPF.MVVM
{
    /// <summary>
    /// Used from Xaml to bind control to collection.
    /// </summary>
    public static class MultiSelect
    {
        static MultiSelect()
        {
            Selector.ItemsSourceProperty.OverrideMetadata(typeof(Selector), new FrameworkPropertyMetadata(ItemsSourceChanged));
        }

        /// <summary>
        /// Returns if the bound control is enabled.
        /// </summary>
        /// <param name="target"></param>
        /// <returns></returns>
        public static bool GetIsEnabled(Selector target)
        {
            return (bool)target.GetValue(IsEnabledProperty);
        }

        /// <summary>
        /// Enables/disables the bound control.
        /// </summary>
        /// <param name="target"></param>
        /// <param name="value"></param>
        public static void SetIsEnabled(Selector target, bool value)
        {
            target.SetValue(IsEnabledProperty, value);
        }

        /// <summary>
        /// True, if enabled.
        /// </summary>
        public static readonly DependencyProperty IsEnabledProperty =
            DependencyProperty.RegisterAttached("IsEnabled", typeof(bool), typeof(MultiSelect), 
                new UIPropertyMetadata(IsEnabledChanged));

        static void IsEnabledChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            var selector = sender as Selector;

            if (selector != null)
            {
                var collectionView = selector.ItemsSource as IMultiSelectCollectionView;

                if (collectionView != null)
                {
                    if ((bool)e.NewValue)
                    {
                        collectionView.AddControl(selector);
                    }
                    else
                    {
                        collectionView.RemoveControl(selector);
                    }
                }
            }
        }

        static void ItemsSourceChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            var selector = sender as Selector;

            if (GetIsEnabled(selector))
            {
                var oldCollectionView = e.OldValue as IMultiSelectCollectionView;
                var newCollectionView = e.NewValue as IMultiSelectCollectionView;

                if (oldCollectionView != null)
                {
                    oldCollectionView.RemoveControl(selector);
                }

                if (newCollectionView != null)
                {
                    newCollectionView.AddControl(selector);
                }
            }
        }
    }
}
    